<template>
  <w-modal 
    ref="WModal"
    title="条形码生成"
    @ok="createQRCode"
  >
    <a-input v-model="inputData" type="textarea" placeholder="请输入..." />
    <br />
    <br />
    <a-select v-model="codeType" style="width: 220px">
      <a-select-option v-for="item in codeTypes" :key="item" :value="item">
        {{ item }}
      </a-select-option>
    </a-select>
    <br />
    <br />
    <div class="code-img-bg">
      <img
        id="com-web-tool-bar-code-img"
        :class="{ 'hide-img': !isSuccess }"
        alt=""
      />
    </div>
  </w-modal>
</template>

<script lang="ts">
import JsBarcode from 'jsbarcode'
import { Vue, Component } from 'vue-property-decorator'
import WModal, { ModalComType } from '@/components/global/modal'

@Component({
  name: 'ComWebToolBarCode',
  components: {
    WModal
  },
})
export default class ComWebToolBarCode extends Vue {
  codeType = 'CODE128'
  codeTypes = [
    'CODE128',
    'CODE128A',
    'CODE128B',
    'CODE128C',
    'EAN13',
    'UPC',
    'EAN8',
    'EAN5',
    'EAN2',
    'CODE39',
    'ITF',
    'ITF14',
    'MSI',
    'MSI10',
    'MSI11',
    'MSI1010',
    'MSI1110',
    'pharmacode',
    'codabar'
  ]

  inputData = ''
  // 是否生成成功
  isSuccess = false

  show () {
    (this.$refs.WModal as ModalComType).show()
  }

  createQRCode () {
    if (!this.inputData) {
      this.$message.error('请输入数据')
      return
    }
    const self = this
    JsBarcode('#com-web-tool-bar-code-img', this.inputData, {
      format: this.codeType,
      valid: (valid: boolean) => {
        self.isSuccess = valid
        if (!valid) {
          this.$message.error('生成条形码失败,请确认输入是否有误')
        }
      }
    })
  }
}
</script>

<style scoped lang="less">
.code-img-bg {
  display: flex;
  justify-content: center;
  img {
    max-width: 100%;
  }
  .hide-img {
    display: none;
  }
}
</style>
